<?php
// 应用公共文件
//随机数
/**
 * @param int $length 随机数长度
 * @param string $num 是否只包含数字
 * @return null|string 返回随机字符串
 */
function codestr($length=4,$num=''){
    $str    = null;
    $strPol = $num==1 ? '123456789' : "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $max    = strlen($strPol)-1;
    for($i=0;$i<$length;$i++){
        $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
    }
    return $str;
}
/**
 * @param $obj
 * @return mixed
 * 对象转换为数组
 */
function objToArray($obj){
    return json_decode(json_encode($obj),true);
}

/**
 * 字符串截取
 * @param $str
 * @param int $start
 * @param $length
 * @param string $charset
 * @param bool|true $suffix
 * @return string
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
    if(function_exists("mb_substr"))
        $slice = mb_substr($str, $start, $length, $charset);
    elseif(function_exists('iconv_substr')) {
        $slice = iconv_substr($str,$start,$length,$charset);
        if(false === $slice) {
            $slice = '';
        }
    }else{
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }
    return $suffix ? $slice.'...' : $slice;
}

/**
 * @param $list
 * @param string $pk
 * @param string $pid
 * @param string $child
 * @param int $root
 * @return array
 * 无限分类 数组转 树形结构
 */
function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) {
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId =  $data[$pid];
            if ($root == $parentId || (isset($data['spid'])&&$data['pid'].'|' == $data['spid'])) {
                $tree[$data[$pk]] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][$data[$pk]] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * @param $str
 * @return string
 * 密码加密
 */
function passwordEncode($str,$code=''){
    return sha1($code.md5($str));
}
/**
 * @param $mobile
 * @return bool
 * 验证手机号码是否正确
 */
function is_mobile($mobile){
    $reg = '/^1[34578][0-9]{9}$/';
    if(!preg_match($reg,$mobile)){
        return false;
    }
    return true;
}
function isUrl($url)
{
    $reg = '/^http[s]?:\/\/[_a-zA-Z0-9-]+(.[_a-zA-Z0-9-]+)*$/';
  if(!preg_match($reg,$url)){
      return false;
  }
    return true;
}
function isEmail($email){
    return filter_var($email,FILTER_VALIDATE_EMAIL);
}
//只能获取一级菜单
function getLinkMenu($menuid,$field='field',$type='select',$selectid=0,$disfield='id',$limit=0,$condition=array()){
    if(!$menuid) return [];
    $map['menuid'] = $menuid;
    $map['status'] = 1;

    if(empty($condition)){
        $condition['pid'] = 0;
    }
    $where = array_merge($map,$condition);
    $obj = model('linkmenu');
    $obj->where($where)->order('ordid asc,id desc');
    if($limit>0){
        $obj->limit($limit);
    }
    $lists =$obj->select();
    $str = '';
    switch($type){
        case 'select':
            $str   = '<select name="'.$field.'" id="'.$field.'">';
            $strs = $menuid !=1 ? '<option value="0">--请选择--</option>' : '';
            $str .=$strs;
            if(!empty($lists)){
                foreach($lists as $v){
                    $s = ($selectid  && $selectid == $v[$disfield]) ? 'selected' : '';
                    $str .= '<option value="'.$v[$disfield].'" '.$s.'>'.$v['name'].'</option>';
                }
            }
            $str .= '</select>';
            break;
        case 'radio':
            if(!empty($lists)){
                foreach($lists as $v){
                    $s = ($selectid && $selectid == $v[$disfield]) ? 'checked' : '';
                    $str .= '<input type="radio" name="'.$field.'" id="'.$field.$v[$disfield].'" value="'.$v['id'].'" '.$s.' /><label for="'.$field.$v['id'].'">'.$v['name'].'</label>';
                }
            }
            break;
        case 'checkbox':
            if(!empty($lists)){
                foreach($lists as $v){
                    $s = (is_array($selectid) && !empty($selectid)) ? (in_array($v[$disfield],$selectid) ?  'checked' : '') : '';
                    $str .= '<input type="checkbox" name="'.$field.'[]" id="'.$field.$v[$disfield].'" value="'.$v[$disfield].'" '.$s.' /><label for="'.$field.$v[$disfield].'">'.$v['name'].'</label>';
                }
            }
            break;
        case 'array':
            $str = $lists;
            break;
            defalut:
            $str   = '<select name="'.$field.'" id="'.$field.'"><option value="0">所有</option>';
            if(!empty($lists)){
                foreach($lists as $v){
                    $s = ($selectid && $selectid == $v[$disfield]) ? 'selected' : '';
                    $str .= '<option value="'.$v[$disfield].'" '.$s.'>'.$v['name'].'</option>';
                }
            }
            $str .= '</select>';
            break;
    }

    return $str;
}
function getUrl($action,$key,$param,$val=''){
    $param[$key] = $val;

    return url($action,$param);
}
function baomingType($key=''){
    $data = [
        1 => '报名看房',
        2 => '降价通知',
        3 => '免费电话',
        4 => '团购报名'
    ];
    $site = cache('site');
    if($site['hongbao']==1){
        $data[5] = '领取红包';
    }
    if($key && array_key_exists($key,$data)){
        return $data[$key];
    }else{
        return $data;
    }
}
function optionStatus($key=''){
    $data = [
      '-1' => '已删除',
        '0' => '待审',
        '1' => '发布',
        '2' => '未通过',
        '3' => '草稿'
    ];
    if(array_key_exists($key,$data)){
        return $data[$key];
    }else{
        return $data;
    }
}
function userModel($key=''){
    $data = [
        1 => '个人会员',
        2 => '经纪人'
    ];
    if($key && array_key_exists($key,$data)){
        return $data[$key];
    }else{
        return $data;
    }
}
function sendEmail($email,$content,$title='密码找回'){
 vendor('phpmailer.PHPMailerAutoload');
    $mail = new \PHPMailer;
//Tell PHPMailer to use SMTP
    $mail->isSMTP();
    $mail->SMTPDebug = 0;
//Ask for HTML-friendly debug output
    $mail->Debugoutput = 'html';
//Set the hostname of the mail server
    $mail->Host = "smtp.163.com";
//Set the SMTP port number - likely to be 25, 465 or 587
    $mail->Port = 25;
//Whether to use SMTP authentication
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = false;
//Username to use for SMTP authentication
    $mail->Username = "luojunyvs@163.com";
//Password to use for SMTP authentication
    $mail->Password = "123456junyvs";
//Set who the message is to be sent from
    $mail->setFrom('luojunyvs@163.com', cache('site')['title']);
//Set an alternative reply-to address
    $mail->addReplyTo('luojunyvs@163.com', cache('site')['title']);
//Set who the message is to be sent to
    $mail->addAddress($email, $email);
//Set the subject line
    $mail->Subject = $title;
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
    $mail->msgHTML($content);
//Replace the plain text body with one created manually
 //$mail->AltBody = 'This is a plain-text message body';
//send the message, check for errors
    if (!$mail->send()) {
        return false;//echo "Mailer Error: " . $mail->ErrorInfo;
    } else {
        return true;
    }
}
function getWeixinConfig(){
    $config = cache('weixin');
    $data = [
        'token'          => $config['weixin_token'],
        'appid'          => $config['weixin_appid'],
        'appsecret'      => $config['weixin_appsecret'],
        'encodingaeskey' => $config['weixin_appkey'],
    ];
    return $data;
}